package com.jie.msmservice.controller;

import com.jie.commonutils.ResultEntity;
import com.jie.msmservice.service.MsmService;
import com.jie.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 短信发送的Controller类
 * @author XieZhiJie
 * @create 2020-10-15 21:06
 */
//@CrossOrigin  // 解决跨域问题
@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {

    private final MsmService msmService;

    // 用于连接redis缓存
    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public MsmController(
            MsmService msmService,
            RedisTemplate<String, String> redisTemplate
    ) {
        this.msmService = msmService;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 发送短信的方法
     * @param phone  用户的手机号码
     * @return       返回短信是否发送成功的信息
     */
    @GetMapping("/send/{phone}")
    public ResultEntity sendMsm(
            @PathVariable("phone") String phone
    ) {

        // 1.从redis中获取验证码, 如果获取到则直接返回(短信验证码存在于redis中5分钟)
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return ResultEntity.ok();
        }

        // 2.如果redis中获取不到值, 则进行阿里云发送
        // 生成随机值, 传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);

        // 调用service发送短信的方法
        Boolean isSend = msmService.send(param, phone);
        if (!isSend) {
            return ResultEntity.error().message("短信发送失败!");
        }
        // 发送成功, 将验证码放入redis中并设置有效时间(5分钟)
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        return ResultEntity.ok();
    }

}
